package deibay.server;

import java.util.Hashtable;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.messages.Message;
import deibay.server.events.Event;
import deibay.server.events.CreateSessionEvent;
import deibay.server.events.ReceivedMessageEvent;
import deibay.server.events.RemoveSessionEvent;
import deibay.users.User;
import deibay.util.Pair;

/**
 * @author   Joel Cordeiro
 */
public class MessageQueue implements EventConsumer{
	
	//private Hashtable<User, LinkedBlockingQueue<Message>> messageQueue = null;
	private BlockingQueue<Pair<User, Message>> messageQueue = null;
	private MessageConsumer consumer = null;
	private Thread tConsumer;
	
	public MessageQueue()
	{
		messageQueue = new LinkedBlockingQueue<Pair<User, Message>>();
		consumer = new MessageConsumer(messageQueue);				
	}
	
	public void init()
	{
		initializeThreads();
		subscribeToEvents();
	}
	
	private void subscribeToEvents() {		
		ServerManager.getInstance().getEventManager().subscribe(this, CreateSessionEvent.class);
		ServerManager.getInstance().getEventManager().subscribe(this, ReceivedMessageEvent.class);
		ServerManager.getInstance().getEventManager().subscribe(this, RemoveSessionEvent.class);
	}
	
	private void initializeThreads()
	{				
		tConsumer = new Thread(consumer);
		tConsumer.start();			

	}

	
	private synchronized void putMessageToQueue(User user, Message message)
	{				
		messageQueue.offer(new Pair<User, Message>(user, message));
	}
	
	
	public void handleEvent(Event event) {
		if(event instanceof CreateSessionEvent)
		{			
		}
		else if(event instanceof ReceivedMessageEvent)
		{			
			Message message = ((ReceivedMessageEvent)event).getReceivedMessageArgs().getMessage();			
			User user = ((ReceivedMessageEvent)event).getReceivedMessageArgs().getUser();			
			putMessageToQueue(user, message);			
		}		
		else if(event instanceof RemoveSessionEvent)
		{
		}
	}		
}
